#include "LOG.hpp"
#include "InetAddr.h"
#include "Socket.hpp"
#include "lockgroup.hpp"

// 1.初始化 port _listen  loop循环中创建rfds位图结构，调用select进行判断，有就绪的，_listenfd调用accept接收新fd，但因为是新的，所以要交给select管理，等待数据到来，方法：把它放到辅助数组，在Hanler一次结束后，继续循环时，通过辅助数组把rfds位图复原
class SelectServer
{
    const static int defaultnums = sizeof(fd_set) * 8;
    const static int defaultfd = -1;

public:
    SelectServer(uint16_t port)
        : _port(port), _listenfd(std::make_unique<TcpSocket>())
    {
        InetAddr addr("0", port);
        _listenfd->BuildListenSocket(addr);

        // 对辅助数组初始化
        for (int i = 0; i < defaultnums; i++)
        {
            _rfds_arr[i] = defaultfd;
        }
        _rfds_arr[0] = _listenfd->sockfd();
    }

    ~SelectServer()
    {
    }


    // _listenfd的处理
    void Acceptfd()
    {
        InetAddr client;
        int fd = _listenfd->AcceptSocket(&client);
        if (fd < 0)
            return;
        LOG(INFO, "accept success: client ip: %s port : %d\n", client.Ip().c_str(), client.Port());
        // 此fd为新连接fd，但现在还不能读，因为它是新的fd，那就要交给select管理。
        // 将fd加入到辅助数据即可。
        int pos = 1;
        for (; pos < defaultnums; pos++)
        {
            if (_rfds_arr[pos] == defaultfd)
                break;
        }
        if (pos == defaultnums)
        {
            // 证明select接收到fd满了,那只能丢弃连接了
            ::close(fd);
            LOG(WARNING, "select buffer full! close connection");
            return;
        }
        else
        {
            _rfds_arr[pos] = fd;
            LOG(INFO, "_rfds_arr buffer add new fd success! new fd: %d", fd);
        }
        //看看现在有几个fd
        LOG(INFO, "now rfdlist: %s", RfdsList().c_str());
    }

    // 普通fd的处理
    void ServiceIO(int pos)
    {
        char buffer[1024];
        ssize_t n = ::recv(_rfds_arr[pos],buffer,sizeof(buffer) - 1,0);
        //对方关闭了连接
        if(n == 0)
        {
            ::close(_rfds_arr[pos]);
            LOG(INFO,"%d is close!",_rfds_arr[pos]);
            _rfds_arr[pos] = defaultfd;
            LOG(DEBUG, "now rfdslist:%s", RfdsList().c_str());
        }
        //出错了
        else if(n < 0)
        {
            ::close(_rfds_arr[pos]);
            LOG(INFO,"%d recv fail",_rfds_arr[pos]);
            _rfds_arr[pos] = defaultfd;
            LOG(DEBUG, "now rfdslist:%s", RfdsList().c_str());
        }
        //正常读数据了
        else
        {
            buffer[n] = 0;
            //做一个回显 
            std::cout << "client say: " << buffer << std::endl;
            std::string echo = "Server Echo# ";
            echo += buffer;
            ::send(_rfds_arr[pos],echo.c_str(),echo.size(),0);

        }
    }

    void Handler(fd_set &rfds)
    {
        for (int i = 0; i < defaultnums; i++)
        {
            if (_rfds_arr[i] == defaultfd)
                continue;

            // 为1说明_rfds_arr[i]是就绪的，是就绪的就需要处理
            if (FD_ISSET(_rfds_arr[i], &rfds))
            {
                // _listenfd的处理
                if (_rfds_arr[i] == _listenfd->sockfd())
                {
                    Acceptfd();
                }

                // 普通fd的处理
                else
                {
                    ServiceIO(i);
                }
            }
        }
    }
    void loop()
    {
        while (1)
        {
            // 先来个位图结构
            fd_set rfds;
            FD_ZERO(&rfds);

            int max_fd = -1;
            // 用辅助数组复原rfds位图，并剔除掉已经处理过的fd
            for (int i = 0; i < defaultnums; i++)
            {
                if (_rfds_arr[i] != defaultfd)
                    FD_SET(_rfds_arr[i], &rfds);

                if (max_fd < _rfds_arr[i])
                    max_fd = _rfds_arr[i];
            }

            struct timeval t = {1, 0};
            int n = select(max_fd + 1, &rfds, nullptr, nullptr, &t);
            switch (n)
            {
            case 0:
                LOG(INFO, "select overtime! %d.%d",t.tv_sec,t.tv_usec);
                break;
            case -1:
                LOG(ERROR, "select error!");
                break;
            default:
                LOG(INFO, "select success!,already fd nums: %d", n);
                Handler(rfds);
                break;
            }
        }
    }

 string RfdsList()
    {
        string rfdlist;
        for (int i = 0; i < defaultnums; i++)
        {
            if (_rfds_arr[i] == defaultfd)
                continue;
            rfdlist += to_string(_rfds_arr[i]);
            rfdlist += " ";
        }
        return rfdlist;
    }
private:
    uint16_t _port;
    unique_ptr<Socket> _listenfd;
    int _rfds_arr[defaultnums];
};